<template>
	<view class="container">
		<!-- 顶部操作栏 -->
		<view class="header">
			<text class="title">数据管理</text>
			<button class="add-btn" @click="handleAdd">+ 添加监管任务</button>
		</view>

		<!-- 搜索框 -->
		<view class="search-box">
			<input type="text" v-model="searchKey" placeholder="搜索名称或任务..." @confirm="loadData" />
			<button @click="loadData">搜索</button>
		</view>

		<!-- 数据列表 -->
		<view class="list">
			<!-- 列表项：优化布局结构 -->
			<view class="list-item" v-for="(item, index) in dataList" :key="item._id" :class="{ 'invalid-task': item.status === '已作废' }">
				<view class="item-content">
					<!-- 左侧内容区：统一垂直排列，优化二维码和按钮布局 -->
					<view class="item-main">
						<!-- 状态标签：过期/作废 -->
						<view class="status-tags">
							<view class="tag expired-tag" v-if="isTaskExpired(item)">已过期</view>
							<view class="tag invalid-tag" v-if="item.status === '已作废'">已作废</view>
						</view>

						<text class="name">{{ item.name }}</text>
						<view class="image-preview" v-if="item.photo && item.photo.url">
							<image :src="item.photo.url" mode="widthFix" @click="previewImage(item.photo.url)"></image>
						</view>
						<text class="task">{{ item.task }}</text>
						
						<!-- 日期范围：优化间距 -->
						<view class="date-range">
							<text>开始: {{ formatDate(item.startDate) }}</text>
							<text>结束: {{ formatDate(item.endDate) }}</text>
						</view>

						<!-- 授权码 + 复制按钮：横向排列，避免换行错乱 -->
						<view class="access-group">
							<text class="access-code">授权码: {{ item.accessCode }}</text>
							<view class="copybtn" @click="copyurl(item.accessCode)">复制</view>
						</view>

						<!-- 二维码：固定尺寸+居中，避免撑开布局 -->
						<view class="qrcode-container">
							<uqrcode 
								ref="uqrcode" 
								canvas-id="qrcode" 
								:value="item.accessCode" 
								:options="options"
							></uqrcode>
						</view>
					</view>

					<!-- 右侧操作按钮：垂直排列，避免水平空间不足 -->
					<view class="item-actions">
						<button 
							size="mini" 
							class="edit-btn" 
							@click="handleEdit(item)"
							v-if="item.status !== '已作废'"
						>编辑</button>
						<button 
							size="mini" 
							class="invalid-btn" 
							@click="handleInvalidate(item)"
							v-if="item.status !== '已作废'" 
						>作废</button>
						<button size="mini" class="delete-btn" @click="handleDelete(item._id)">删除</button>
					</view>
				</view>

				<!-- 图片预览：固定宽度，与左侧内容对齐 -->
			
			</view>

			<!-- 空状态 -->
			<view class="empty" v-if="dataList.length === 0 && !loading">
				<text>暂无数据</text>
			</view>

			<!-- 加载中 -->
			<view class="loading" v-if="loading">
				<uni-icons type="reload" size="50"></uni-icons>
				<text>加载中...</text>
			</view>
		</view>

		<!-- 新增/编辑弹窗 -->
		<uni-popup ref="edit" mode="bottom" :height="600">
			<view class="dialog">
				<view class="dialog-title">{{ isEdit ? '编辑数据' : '新增数据' }}</view>

				<view class="form">
					<uni-forms ref="form" :model="formData" :rules="rules">
						<uni-forms-item label="名称" name="name">
							<uni-easyinput v-model="formData.name" placeholder="请输巡检员姓名"></uni-easyinput>
						</uni-forms-item>

						<uni-forms-item label="开始日期" name="startDate">
							<uni-datetime-picker v-model="formData.startDate" type="date" placeholder="选择开始日期"></uni-datetime-picker>
						</uni-forms-item>

						<uni-forms-item label="结束日期" name="endDate">
							<uni-datetime-picker v-model="formData.endDate" type="date" placeholder="选择结束日期"></uni-datetime-picker>
						</uni-forms-item>

						<uni-forms-item label="任务描述" name="task">
							<uni-easyinput v-model="formData.task" type="textarea" placeholder="请输入任务描述"></uni-easyinput>
						</uni-forms-item>

						<uni-forms-item label="图片上传">
							<uni-file-picker
								ref="photo"
								v-model="photos"
								title="相片"
								:limit="1"
								file-mediatype="image"
								:auto-upload="false"
								mode="grid"
								cloudPath="inspector"
								return-type="Object"
								@select="select"
								@progress="progress"
								@success="success"
								@fail="fail"
							>
								<view class="" style="font-size: 50rpx">+</view>
							</uni-file-picker>
						</uni-forms-item>
					</uni-forms>
				</view>

				<view class="dialog-btns">
					<button class="cancel-btn" @click="$refs.edit.close()">取消</button>
					<button class="confirm-btn" @click="suresubmit">{{ isEdit ? '更新' : '保存' }}</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
const db = uniCloud.databaseForJQL();
const url = 'env-00jxu2inwr5m-static.normal.cloudstatic.cn/#/?type=ycjg';

export default {
	components: {
		// 确保已引入uni-ui组件（uqrcode、uni-popup等）
	},
	data() {
		return {
			photos: [],
			dataList: [],
			loading: false,
			uploadLoading: false, // 图片上传中loading
			uploadedPhoto: null, // 存储上传成功后的图片信息（fileID + url）
			searchKey: '',
			dialogVisible: false,
			isEdit: false,
			currentId: '',
			formData: {
				uid: '',
				name: '',
				startDate: '',
				endDate: '',
				task: '',
				accessCode: '',
				photo: { url: '', fileID: '' },
				status: '正常' // 新增：任务状态（正常/已作废），默认正常
			},
			options: {
				margin: 5, // 优化二维码边距，避免过大
				size: 120 // 固定二维码尺寸
			},
			rules: {
				name: {
					rules: [{ required: true, errorMessage: '请输入名称' }]
				},
				uid: {
					rules: [{ required: true, errorMessage: '请输入用户ID' }]
				},
				startDate: {
					rules: [{ required: true, errorMessage: '请选择开始日期' }]
				},
				endDate: {
					rules: [{ required: true, errorMessage: '请选择结束日期' }]
				},
				photo: {
					rules: [{
						required: true,
						validator: (rule, value, callback) => {
							if (!value || !value.url) {
								callback('请上传图片');
							} else {
								callback();
							}
						},
						errorMessage: '请上传图片'
					}]
				}
			}
		};
	},
	onLoad(res) {
		this.loadData();
	},
	methods: {
		// 加载数据：保持原有逻辑
		async loadData() {
			this.loading = true;
			try {
				const collection = db.collection('inspector');
				let query = collection.where({});

				// 搜索功能
				if (this.searchKey) {
					query = query.where({
						$or: [{ name: new RegExp(this.searchKey, 'i') }, { task: new RegExp(this.searchKey, 'i') }]
					});
				}

				const res = await query.get();
				// 确保status字段存在（兼容旧数据）
				this.dataList = res.data.map(item => ({
					status: item.status || '正常', // 旧数据默认正常
					...item
				}));
			} catch (err) {
				console.error('加载数据失败', err);
				uni.showToast({ title: '加载失败', icon: 'none' });
			} finally {
				this.loading = false;
			}
		},

		// 图片上传相关：保持原有逻辑
		select(e) {
			console.log('选择', e);
			console.log(this.photos);
		},
		progress(e) {
			console.log(e);
		},
		success(e) {
			this.formData.photo.url = e.tempFiles[0].url;
			this.formData.photo.fileID = e.tempFiles[0].fileID;
			this.submitForm();
		},
		fail(e) {
			console.log('失败', e);
		},

		// 复制授权码：保持原有逻辑
		copyurl(code) {
			uni.setClipboardData({
				data: code,
				success: () => uni.showToast({ title: '复制成功' })
			});
		},

		// 格式化日期：保持原有逻辑
		formatDate(date) {
			if (!date) return '';
			const d = new Date(date);
			return `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, '0')}-${d.getDate().toString().padStart(2, '0')}`;
		},

		// 新增：判断任务是否过期（当前时间 > 结束时间）
		isTaskExpired(item) {
			if (!item.endDate) return false;
			const currentTime = Date.now();
			const endTime = new Date(item.endDate).getTime();
			return currentTime > endTime;
		},

		// 新增：任务作废功能
		async handleInvalidate(item) {
			uni.showModal({
				title: '确认作废',
				content: '作废后任务将无法编辑，是否继续？',
				confirmColor: '#ff3b30',
				success: async (res) => {
					if (res.confirm) {
						try {
							// 更新数据库状态为「已作废」
							await db.collection('inspector').doc(item._id).update({
								status: '已作废'
							});
							uni.showToast({ title: '作废成功' });
							this.loadData(); // 重新加载数据
						} catch (err) {
							console.error('作废失败', err);
							uni.showToast({ title: '作废失败', icon: 'none' });
						}
					}
				}
			});
		},

		// 新增数据：保持原有逻辑，新增status默认值
		handleAdd() {
			this.formData = {
				uid: '',
				name: '',
				startDate: '',
				endDate: '',
				task: '',
				accessCode: '',
				photo: { url: '', fileID: '' },
				status: '正常' // 默认正常状态
			};
			this.isEdit = false;
			this.currentId = '';
			this.$refs.edit.open();
		},

		// 编辑数据：新增status赋值
		handleEdit(item) {
			this.isEdit = true;
			this.currentId = item._id;

			// 填充表单，包含status字段
			this.formData = {
				uid: item.uid || '',
				name: item.name || '',
				startDate: item.startDate ? new Date(item.startDate).toISOString().split('T')[0] : '',
				endDate: item.endDate ? new Date(item.endDate).toISOString().split('T')[0] : '',
				task: item.task || '',
				accessCode: item.accessCode || '',
				photo: item.photo || { url: '', fileID: '' },
				status: item.status || '正常' // 赋值状态
			};
			this.$refs.edit.open();
		},

		// 提交表单：保持原有逻辑，提交时携带status
		async suresubmit() {
			if (this.isEdit) {
				this.submitForm();
			} else {
				const valid = await this.$refs.form.validate();
				if (!valid) return;
				this.$refs.photo.upload();
			}
		},

		async submitForm() {
			try {
				this.uploadLoading = true;

				// 表单验证
				const valid = await this.$refs.form.validate();
				if (!valid) return;

				// 处理日期格式
				const form = { ...this.formData };
				form.uid = Date.now().toString();
				form.startDate = new Date(form.startDate);
				form.endDate = new Date(form.endDate);
				form.accessCode = `${url}&uid=${form.uid}`;
				// 携带status字段提交（新增/编辑均保留状态）

				// 提交数据
				const collection = db.collection('inspector');
				if (this.isEdit) {
					await collection.doc(this.currentId).update(form);
					uni.showToast({ title: '更新成功' });
				} else {
					await collection.add(form);
					uni.showToast({ title: '添加成功' });
				}

				// 关闭弹窗+重新加载
				this.$refs.edit.close();
				this.loadData();

			} catch (err) {
				console.error('提交失败：', err.message);
				uni.showToast({ title: err.message || '操作失败', icon: 'none' });
			} finally {
				this.uploadLoading = false;
			}
		},

		// 删除数据：保持原有逻辑
		async handleDelete(id) {
			uni.showModal({
				title: '提示',
				content: '确定要删除这条数据吗？',
				success: async (res) => {
					if (res.confirm) {
						try {
							await db.collection('inspector').doc(id).remove();
							uni.showToast({ title: '删除成功' });
							this.loadData();
						} catch (err) {
							console.error('删除失败', err);
							uni.showToast({ title: '删除失败', icon: 'none' });
						}
					}
				}
			});
		},

		// 预览图片：保持原有逻辑
		previewImage(url) {
			uni.previewImage({
				urls: [url]
			});
		}
	}
};
</script>

<style lang="scss" scoped>
.container {
	padding: 8px;
	background-color: #e7e7e7;
	min-height: 100vh;
}

.header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 10px 0;
	border-bottom: 1px solid #eee;
	margin-bottom: 10px;
}

.title {
	font-size: 18px;
	font-weight: bold;
}

.add-btn {
	background-color: #007aff;
	color: white;
	padding: 5px 10px;
	border-radius: 4px;
}

.search-box {
	display: flex;
	gap: 5px;
	margin-bottom: 10px;
}

.search-box input {
	flex: 1;
	border: 1px solid #eee;
	padding: 8px;
	border-radius: 4px;
}

/* 列表容器：统一间距 */
.list {
	display: flex;
	flex-direction: column;
	gap: 12px;
}

/* 列表项：优化整体样式，已作废任务加灰色滤镜 */
.list-item {
	background-color: white;
	border-radius: 6px;
	padding: 12px;
	box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
	transition: all 0.2s;

	&.invalid-task {
		opacity: 0.7;
		filter: grayscale(0.5); // 已作废任务灰色化
	}
}

/* 内容区：横向布局，左右间距 */
.item-content {
	display: flex;
	flex-direction: column;
	justify-content: space-between;
	align-items: flex-start;
	gap: 12px;
	margin-bottom: 12px;
}

/* 左侧主内容区：垂直排列，统一间距 */
.item-main {
	flex: 1;
	display: flex;
	flex-direction: column;
	gap: 6px;
}

/* 状态标签容器：横向排列，标签间距 */
.status-tags {
	display: flex;
	gap: 6px;
	margin-bottom: 4px;
}

/* 状态标签通用样式 */
.tag {
	font-size: 12px;
	padding: 2px 6px;
	border-radius: 4px;
	color: white;
	font-weight: 500;
}

/* 过期标签：橙色 */
.expired-tag {
	background-color: #ff9500;
}

/* 作废标签：灰色 */
.invalid-tag {
	background-color: #999;
}

.name {
	font-size: 16px;
	font-weight: bold;
}

.task {
	font-size: 14px;
	color: #666;
	line-height: 1.4;
}

/* 日期范围：优化颜色和间距 */
.date-range {
	display: flex;
	gap: 12px;
	font-size: 12px;
	color: #888;
}

/* 授权码+复制按钮：横向排列，对齐 */
.access-group {
	display: flex;
	flex-direction: column;
	align-items: center;
	gap: 8px;
	margin-top: 4px;
}

.access-code {
	font-size: 13px;
	color: #007aff;
	flex: 1;
	white-space: nowrap;
	overflow: hidden;
	text-overflow: ellipsis; // 过长授权码省略
}

/* 复制按钮：优化尺寸，适应列表 */
.copybtn {
	padding: 6px 12px;
	width: auto; // 取消固定宽度，自适应内容
	font-size: 14px;
	background-color: #007aff;
	border-radius: 4px;
	color: white;
	cursor: pointer;
	transition: all 0.2s;

	&:active {
		background-color: #4cd964;
		transform: scale(0.95);
	}
}

/* 二维码容器：固定尺寸+居中 */
.qrcode-container {
	display: flex;
	justify-content: center;
	margin-top: 8px;

	>>> .uqrcode {
		width: 120px !important;
		height: 120px !important;
	}
}

/* 右侧操作按钮：垂直排列，统一样式 */
.item-actions {
	display: flex;

	gap: 6px;
}

.edit-btn {
	background-color: #4cd964;
	color: white;
}

/* 作废按钮：灰色 */
.invalid-btn {
	background-color: #999;
	color: white;
}

.delete-btn {
	background-color: #ff3b30;
	color: white;
}

/* 图片预览：固定宽度，避免过大 */
.image-preview {
	margin-top: 8px;
	padding-top: 8px;
	border-top: 1px dashed #eee;

	image {
		width: 120px;
		height: auto;
		border-radius: 4px;
	}
}

.empty {
	text-align: center;
	padding: 50px 0;
	color: #999;
	font-size: 14px;
}

.loading {
	text-align: center;
	padding: 50px 0;
	display: flex;
	flex-direction: column;
	align-items: center;
	gap: 8px;
}

.dialog {
	background-color: #fff;
	padding: 10px;
}

.dialog-title {
	font-size: 17px;
	font-weight: bold;
	padding: 5px 0;
	border-bottom: 1px solid #eee;
	margin-bottom: 10px;
}

.form {
	margin-bottom: 15px;
}

.dialog-btns {
	display: flex;
	gap: 10px;
	margin-top: 10px;
}

.cancel-btn {
	flex: 1;
	background-color: #f5f5f5;
	color: #333;
}

.confirm-btn {
	flex: 1;
	background-color: #007aff;
	color: white;
}
</style>